from rest_framework import serializers
from .models import User, Address
import re
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
from celery_tasks.email.tasks import send_verify_email
from goods.models import SKU


class UserCreateSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    # 用户名
    username = serializers.CharField(min_length=5, max_length=20, error_messages={
        'min_length': '用户名不能小于5个字符',
        'max_length': '用户名不能大于20个字符'
    })

    # 验证
    def validate_username(self, value):
        count = User.objects.filter(username=value).count()
        if count:
            raise serializers.ValidationError('用户已经存在了')
        return value

    mobile = serializers.CharField()

    # 验证
    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}', value):
            raise serializers.ValidationError('手机号格式不正确！')
        count = User.objects.filter(mobile=value).count()
        if count:
            raise serializers.ValidationError('手机号已经存在了！')
        return value

    password = serializers.CharField(write_only=True, min_length=8, max_length=20, error_messages={
        'min_length': '密码不能少于8个字符',
        'max_length': '密码不能大于20个字符',
    })
    password2 = serializers.CharField(write_only=True, min_length=8, max_length=20, error_messages={
        'min_length': '密码不能少于8个字符',
        'max_length': '密码不能大于20个字符',
    })
    allow = serializers.CharField(write_only=True)
    sms_code = serializers.CharField(write_only=True)
    # 增加代码1：token字段
    token = serializers.CharField(label='登录状态token', read_only=True)

    def validate_sms_code(self, value):
        if not re.match(r'^\d{6}$', value):
            raise serializers.ValidationError('短信验证码的格式不正确')
        return value

    def validate(self, attrs):
        password = attrs.get('password')
        password2 = attrs.get('password2')
        if password != password2:
            raise serializers.ValidationError('密码不一致')
        # 链接数据库redis获取短信验证码
        redis_cli = get_redis_connection('verify_code')
        sms_code = redis_cli.get('sms_code' + attrs.get('mobile'))
        sms_request = attrs.get('sms_code')
        if not sms_code:
            raise serializers.ValidationError('验证码已经过期了')
        redis_cli.delete('sms_code' + attrs.get('mobile'))
        if sms_code.decode() != sms_request:
            raise serializers.ValidationError('短信验证码不正确')
        return attrs

    # 添加数据
    def create(self, validated_data):
        user = User()
        user.mobile = validated_data.get('mobile')
        user.username = validated_data.get('username')
        user.set_password(validated_data.get('password'))
        user.save()
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return userz


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详细信息序列化器
    """

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class EmailSerializer(serializers.ModelSerializer):
    """
    邮箱序列化器
    """

    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        email = validated_data['email']
        instance.email = validated_data['email']
        instance.save()

        # 生成验证链接
        verify_url = instance.generate_verify_email_url()
        # 发送验证邮件
        send_verify_email.delay(email, verify_url)

        return instance


class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    # 在模型类中定义了三个关系属性，默认输出主键，此处指定输出字符串
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    # 定义了外键后，默认会有***_id的属性，如果希望对隐藏属性进行输出，需要明确指定
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """
        保存
        """
        # 其它数据都是由客户端传递的，但是没有传递用户对象
        # 此时地址的用户对象，应该是当前登录的用户
        # 获取当前便当的用户：request.user
        # self.context===>字典，当视图向序列化器中传递数据时，数据在保存在context中
        validated_data['user'] = self.context['request'].user
        # 调用父类的创建方法，ModelSerializer已经实现了这个方法
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """

    class Meta:
        model = Address
        fields = ('title',)


class AddUserBrowsingHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)
    # print(111111111111111111111111111111111111111)

    def validate_sku_id(self, value):
        sku_id = SKU.objects.get(pk=value)
        if not sku_id:
            raise serializers.ValidationError('商品已经下架！')
        print(value)
        return value

    def create(self, validated_data):
        redis_cli = get_redis_connection('history')
        # print(222222222222222222222222222222222222)
        key = 'history%d' % self.context['request'].user.id
        sku_id = validated_data.get('sku_id')

        # redis_cli.lrem(key, 0, sku_id)
        # redis_cli.lpush(key, sku_id)
        # redis_cli.ltrim(key, 0, 4)
        # 使用管道，减少与数据库的交互
        pl = redis_cli.pipeline()
        pl.lrem(key, 0, sku_id)
        pl.lpush(key, sku_id)
        pl.ltrim(key, 0, 4)
        pl.execute()
        return validated_data
